<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
    
      <el-form-item label="图片归档" prop="fileClassify">
        <el-select 
          v-model="queryParams.fileClassify" 
          placeholder="请选择状态"
          clearable 
        >
          <el-option 
            v-for="dict in fileClassifyList"
            :key="dict.code" 
            :label="dict.name" 
            :value="dict.code" 
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">刷新</el-button>
      </el-form-item>
      
    </el-form>
<!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
     
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>
<!-- 数据列表 -->
    <el-table v-loading="loading" :data="imageGalleryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" width="70"/>      
      <el-table-column label="文件名" align="center" prop="fileName" width="80" />
      <el-table-column label="存储路径" align="center" prop="filePath" width="100" >  
        <template #default="scope" >      
          <img v-if="scope.row.filePath" :src="scope.row.filePath" class="avatar" />
        </template>
      </el-table-column>
      <el-table-column label="图片大小" align="center" prop="fileSize" width="80"/>
      <el-table-column label="文件类型" align="center" prop="mimeType" width="100"/>
      <el-table-column label="图片归类" align="center" prop="fileClassify" width="80" >
        <template #default="scope" >      
          <span>{{ fileClassify2codeToName(scope.row.fileClassify)}}</span>
        </template>
      </el-table-column>
  
      <el-table-column label="排序序号" align="center" prop="sortOrder" width="80"/>
      <!--
      <el-table-column label="文章关联观点" align="center" prop="relatedViewpoints" width="70"/>
      -->
      <el-table-column label="设计项目" align="center" prop="designProject" width="150"/>
      <el-table-column label="作品设计类型" align="center" prop="designType" width="140" >
        <template #default="scope" >      
          <span>{{ designType2codeToName(scope.row.designType)}}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="状态" align="center" prop="isVisible">
        <template #default="scope">
          <span>{{ scope.row.isVisible==1?'使用中':'禁用中'}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="初始上传时间" align="center" prop="createdTime" width="100">
        <template #default="scope">
          <span>{{ dayjs(scope.row.updatedTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" align="center" prop="updatedTime" width="100">
        <template #default="scope">
          <span>{{ dayjs(scope.row.updatedTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
    <el-pagination
      v-show="total>0"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="queryParams.pageNum"
      :page-sizes="[10,15,20,25, 30]"
      :page-size="queryParams.pageSize"
      layout="total,sizes, prev, pager, next"
      :total="total">
    </el-pagination>
  </div>


    <!-- 添加图片库对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="imageGalleryRef" :model="form" :rules="rules" label-width="100px">
        
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入展示文件名" />
        </el-form-item>

        <el-form-item label="简短标题" prop="shortDesc">
          <el-input v-model="form.shortDesc" placeholder="请输入简短标题" />
        </el-form-item>
        
        <el-form-item label="文件细节描述" prop="descDetail">
          <el-input  type="textarea"
                  style="width: 100%"
                  :autosize="{ minRows: 3 }"
                  v-model="form.descDetail" placeholder="请输入文件细节描述" />
        </el-form-item>

        <el-form-item label="图片归档" prop="fileClassify">
          <el-select 
            v-model="form.fileClassify" 
            placeholder="请选择图片归类"
            clearable 
          >
            <el-option 
              v-for="dict in fileClassifyList"
              :key="dict.code" 
              :label="dict.name" 
              :value="dict.code" 
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="关联观点ID" prop="relatedViewpoints" v-if="form.fileClassify==='GD'">
          <el-select 
            v-model="form.relatedViewpoints" 
            placeholder="请选择关联观点ID"
            clearable 
          >
            <el-option 
              v-for="dict in imageGdList"
              :key="dict.id" 
              :label="dict.fileName" 
              :value="dict.id" 
            />
          </el-select>
        </el-form-item> -->
        
        <el-form-item label="设计项目" prop="designProject" v-if="form.fileClassify==='ZP'">
          <el-input v-model="form.designProject" placeholder="请输入设计项目名" />
        </el-form-item>

        <el-form-item label="设计类型" prop="designType" v-if="form.fileClassify==='ZP'">
          <el-select 
            v-model="form.designType" 
            placeholder="请选择图片归类"
            clearable 
          >
            <el-option 
              v-for="dict in designTypeList"
              :key="dict.code" 
              :label="dict.name" 
              :value="dict.code" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="图片" prop="filePath">
          <el-upload
              class="avatar-uploader"
              :action="imgUpload.url"
              :headers="imgUpload.headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"             
          >            
            <el-container v-if="form.fileClassify === 'ZP'" class="el-container">
              <img v-if="imgArray" v-for="(img,index) in imgArray" :src="img.filePath" :key="index" class="avatar" />
              <el-icon  class="avatar-uploader-icon" ></el-icon>
            </el-container>
            <el-row v-else>
              <img v-if="form.filePath" :src="form.filePath" class="avatar" />
              <el-icon  v-else class="avatar-uploader-icon" ></el-icon>
            </el-row>           
          </el-upload>
        </el-form-item>

        <el-form-item  v-if="form.fileClassify==='GD'">
          <WangEditor v-model="form.wzContent" />
        </el-form-item>

      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    

    <!-- 修改图片库对话框 -->
    <el-dialog :title="titleupdate" v-model="openupdate" width="500px" append-to-body>
      <el-form ref="imageGalleryRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入原始文件名" disabled/>
        </el-form-item>

        <el-form-item label="排序序号" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入指定交换的排序号" />
        </el-form-item>
     
        <el-form-item label="图片归档" prop="fileClassify">
          <el-select 
            v-model="form.fileClassify" 
            placeholder="请选择状态"
            clearable 
          >
            <el-option 
              v-for="dict in fileClassifyList"
              :key="dict.code" 
              :label="dict.name" 
              :value="dict.code" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="图片" prop="filePath" class="avatar-uploader">          
            <img v-if="form.filePath" :src="form.filePath" class="avatar" />
        </el-form-item>

       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="ImageGallery">
import { ref, reactive,getCurrentInstance,toRefs,watch } from 'vue'
import { listImageGallery, getImageGallery,  addImageGallery, updateImageGallery,delImageGallerybatch } from "@/api/gallery";
import { useUserStore } from '@/store/modules/user'
import WangEditor from '@/components/risetext/WangEditor.vue'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance();

const fileClassifyList = ref([
  {"code":"SYBANNER","name":"首页轮播图"},
  {"code":"SY","name":"首页"},
  {"code":"YW","name":"业务页"},
  {"code":"GY","name":"关于页"},
  {"code":"GYMEMBER","name":"关于页的主创成员"},
  {"code":"GD","name":"观点页"},
  {"code":"ZP","name":"作品"},
  {"code":"LX","name":"联系"}
]);

const designTypeList=ref([
{"code":1,"name":"品牌IP设计"},
{"code":2,"name":"UI/UX设计"},
{"code":3,"name":"活动展会设计"},
{"code":4,"name":"电商设计"},
{"code":5,"name":"包装设计"}
])

const imageGalleryRef=ref(null)
const queryRef=ref(null)

const imageGalleryList = ref([]);
// const imageGdList = ref([]);

const isIconVisible = ref(true); // 控制显示状态 
const open = ref(false);
const openupdate = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const titleupdate = ref("");

const userStore = useUserStore()
const token = userStore.token

const imgArray=ref([])

const data = reactive({
  form: {
    fileName:null,
    shortDesc:null,
    descDetail:null,
    fileClassify:null,
    relatedViewpoints:null,
    designType:null,
    filePath:null, 
    imgArray:[]
  },
  queryParams: 
   {
    pageNum: 1,
    pageSize: 10,
    fileName: null,
    filePath: null,
    fileSize: null,
    fileClassify: null,
    relatedViewpoints:null,
    mimeType: null,
    sortOrder: null,
    isVisible: null,
    createdTime: null,
    updatedTime: null
  },
  imgUpload: {
    // 设置上传的请求头部
    headers: {
      'access-token':token
      // Authorization: "Bearer" + getToken(),
    },
    // 图片上传的方法地址:
    url: "/admin/file/upload"
  },
  rules: {
    fileName: [
      { required: true, message: "原始文件名不能为空", trigger: "blur" }
    ],
    filePath: [
      { required: true, message: "存储路径不能为空", trigger: "blur" }
    ],
    fileSize: [
      { required: true, message: "图片大小(字节)不能为空", trigger: "blur" }
    ],
    fileClassify: [
      { required: true, message: "请选择图片归类", trigger: "change" }
    ],
    designProject: [
      { required: true, message: "请填写设计项目", trigger: "blur" }
    ],
    designType: [
      { required: true, message: "请选择设计类型", trigger: "change" }
    ]
  }
});

const { queryParams, form,imgUpload, rules } = toRefs(data);


// 转换为 Map 
const fileClassifyMap = new Map(
  fileClassifyList.value.map(item  => [item.code, item.name])
);
function fileClassify2codeToName(fileClassify){  
  return fileClassifyMap.get(fileClassify)
}

// 转换为 Map 
const designTypeMap = new Map(
  designTypeList.value.map(item  => [item.code, item.name])
);
function designType2codeToName(designType){  
  return designTypeMap.get(designType)
}


//上传
function handleAvatarSuccess (response, uploadFile) {
  if(form.value.fileClassify=='ZP'){
    let filePath = response.data.filePath
    let fileSize = response.data.fileSize
    let mimeType = response.data.mimeType
    imgArray.value.push({'filePath':filePath,'fileSize':fileSize,'mimeType':mimeType})
  }else{
    form.value.filePath = response.data.filePath
    form.value.fileSize = response.data.fileSize
    form.value.mimeType = response.data.mimeType
  }

}

function handleCurrentChange(pageNum){
  queryParams.value.pageNum=pageNum
  getList()
}

function handleSizeChange(pageSize){
  queryParams.value.pageSize=pageSize
  getList()
}


/** 查询图片库列表 */
function getList() {
  loading.value = true;  
  listImageGallery(queryParams.value).then(response => {
    imageGalleryList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openupdate.value = false;
  reset();
}

// 表单重置
function reset() {
 form.value = {
    id:null,
    fileName:null,
    shortDesc:null,
    descDetail:null,
    fileClassify:null,
    relatedViewpoints:null,
    designType:null,
    filePath:null, 
    imgArray:[]
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加图片库";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id 
  getImageGallery(_id).then(response => {
    form.value = response.data;
    openupdate.value = true;
    titleupdate.value = "修改图片库";
  });
}

/** 提交按钮 */
function submitForm() {
  if (form.value.id != null) {
    updateImageGallery(form.value.id,form.value.sortOrder,form.value.fileClassify).then(response => {
      openupdate.value = false;
      getList();
    });
  } else {
    if(form.value.fileClassify=='ZP'){
      form.value.imgArray=imgArray.value;
    }
    addImageGallery(form.value).then(response => {
      open.value = false;
      getList();
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  const flag = confirm('是否确认删除图片库编号为"' + _ids + '"的数据项？')
  if(flag){      
      delImageGallerybatch(_ids.toString());
      getList();
  }  
  
}

getList()

//  watch(() => form.value.fileClassify,(newValue,oldValue) => {
//     if(newValue === 'WZGD'){
//       queryParams.value.fileClassify='GD'
//       queryParams.value.pageSize=1000
//       listImageGallery(queryParams.value).then(response => {
//         imageGdList.value = response.data.records;
//       });
//     }
//   })

</script>

<style scoped>
.avatar-uploader{
  width: 80%;
}
.avatar-uploader .avatar {
  width: 90px;
  height: 90px;
  display: block;
}

.cell .avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>

<style>
.avatar-uploader{
  width: 98%!important;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  text-align: center;
}

 .el-container{
    /* width: 540px; */
    display: block;
 }

.el-container img{
  float:left;
}
</style>
